package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileTemplate;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.service.BaiduScanService;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author 陈辉
 * @data 2024 10:21
 */
@Service
public class BaiduScanServiceImpl implements BaiduScanService {

    @Autowired
    private MinIOFileTemplate minIOFileTemplate;
    @Autowired
    private Map<String,String> localCacheMap;

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 调用百度云内容审核接口审核文本信息
     *
     * @param text
     * @return 审核结果类型，可取值1、2、3、4，分别代表1：合规，2：不合规，3：疑似，4：审核失败
     */
    @Override
    public Integer scanText(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            //先去缓存中取access_token
            String accessToken = localCacheMap.get("accessToken");
            //缓存中取不到，再调百度API获取access_token
            if (StringUtils.isEmpty(accessToken)){
                accessToken = getAccessToken();
                if (StringUtils.isNotEmpty(accessToken)){
                    //再将access_token添加到缓存
                    localCacheMap.put("accessToken",accessToken);
                }else {
                    throw new CustomException(AppHttpCodeEnum.BAIDU_ACCESS_ERROR);
                }
            }
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return JSONObject.parseObject(result).getInteger("conclusionType");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 4;   //调用百度失败，转人工审核
    }

    /**
     * 调用百度云内容审核接口审核文本信息
     *
     * @param imgUrl
     * @return 审核结果类型，可取值1、2、3、4，分别代表1：合规，2：不合规，3：疑似，4：审核失败
     */
    @Override
    public Integer scanImg(String imgUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            // 将图片数据从minio中下载下来
            byte[] imgData = minIOFileTemplate.downLoadFile(imgUrl);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            //先去缓存中取access_token
            String accessToken = localCacheMap.get("accessToken");
            //缓存中取不到，再调百度API获取access_token
            if (StringUtils.isEmpty(accessToken)){
                accessToken = getAccessToken();
                if (StringUtils.isNotEmpty(accessToken)){
                    //再将access_token添加到缓存
                    localCacheMap.put("accessToken",accessToken);
                }else {
                    throw new CustomException(AppHttpCodeEnum.BAIDU_ACCESS_ERROR);
                }
            }
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return JSONObject.parseObject(result).getInteger("conclusionType");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 4;   //调用百度失败，转人工审核
    }



    //调用百度API，获取access_token
    private String getAccessToken(){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=eY78K09ILZxPG21SuroaZ2sf&client_secret=GzC65qkDDqtPuUzw9pH7R2RfqnfhZ4Nr&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String res = response.body().string();
            System.out.println(res);
            return JSONObject.parseObject(res).getString("access_token");
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 定期清理本地缓存
     */
    @Scheduled(cron = "* * 0 1/15 * ?")
    @PostConstruct
    public void clearLocalCacheMap(){
        localCacheMap.clear();
    }

}